package com.mk.cloud.pt.service.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mk.cloud.common.domain.*;
import com.mk.cloud.common.enums.ConfigCode;
import com.mk.cloud.common.enums.GlobalValues;
import com.mk.cloud.common.interceptor.header.HeaderService;
import com.mk.cloud.common.util.DateUtils;
import com.mk.cloud.common.util.S2;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.util.S;

import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 关于奖励的发放
 */
public class RewardService extends HeaderService{

    @Inject
    private PProduct.Mapper pProduceMapper;
    @Inject
    private PUser.Mapper pUserMapper;
    @Inject
    private PReward.Mapper pRewardMapper;
    @Inject
    private PWalletFlow.Mapper pWalletFlowMapper;

    /**
     * 发放分区奖励
     * 1.统计查询符合分区奖励的用户
     */
    @GetAction("sendPkReward.jsontest")
    public void sendPkReward(String coid){
        JSONArray array = JSON.parseArray(ConfigCode.valueOf("FISSION_PK_REWARD").value(coid));
        System.out.println(ConfigCode.valueOf("FISSION_PK_REWARD").value(coid));
        Integer min = Integer.MAX_VALUE;
        for(Object obj:array){
            JSONArray arr = (JSONArray) obj;
            min = Integer.min(min,arr.getInteger(0));
        }
        System.out.println(min);


    }


    //region 实物奖励 开始
    /**
     * 当审核通过时执行发放实物奖励
     * @param fuserid 奖励接收人
     */
    public void sendObjectReward(String fuserid, String coid){
        String rewardpercent = ConfigCode.valueOf("FIRST_ORDER_REWARD").value(coid);
        if(new BigDecimal(rewardpercent).compareTo(BigDecimal.ZERO)<=0){
            return;
        }
        String rdescribe = "现场签单总额"+rewardpercent+"%产品返利";
        PReward reward = new PReward();
        reward.setRid(S2.UUID());
        reward.setFuserid(fuserid);
        reward.setCreatetime(DateUtils.getTimeNow());
        reward.setIsvalid(GlobalValues.FLAG_YES.value());
        reward.setCoid(coid);
        reward.setRdescribe(rdescribe);
        PUser user = pUserMapper.single(fuserid);
        reward.setPscode(user.getPscode());
        pRewardMapper.insert(reward);
    }
    //endregion 实物奖励 结束


    //region 现金奖励 开始
    /**
     * 根据订单发奖励
     * @param order
     */
    public void reward(POrder order,PUser user){
        PProduct product = pProduceMapper.single(order.getPdid());
        switch (product.getPdtype()){
            //新店体验
            case "0" : rewardNew(order,user); break;
//            case "1" : break;
//            case "2" : break;
            //爆品体验
            case "3" : rewardBP(order,user); break;
        }
    }

    /**
     * 新店体验奖励
     * @param order
     */
    private void rewardNew(POrder order,PUser user){
        //如果当前登录人是第三级推广人
        if(S.eq(user.getPlevel(),GlobalValues.PLEVEL_3.value())){
            if(S.isNotBlank(user.getFuserid1())){//直接推广人
                sendReward(user,user.getFuserid1(),order.getOrderamount(),"INTRODUCTION_REWARD2","二级推广三级,二级得到的奖励",order);
            }
            if(S.isNotBlank(user.getFuserid2())){//间接推广人
                sendReward(user,user.getFuserid2(),order.getOrderamount(),"INTRODUCTION_REWARD1","二级推广三级,一级(合伙人)得到的奖励",order);
            }
        } else if(S.eq(user.getPlevel(),GlobalValues.PLEVEL_2.value())){
            if(S.isNotBlank(user.getFuserid1())) {//直接推广人
                sendReward(user,user.getFuserid1(), order.getOrderamount(), "INTRODUCTION_REWARD", "一级(合伙人)推广二级,一级(合伙人)得到的奖励",order);
            }
        }
    }

    /**
     * 发放奖励
     * @param fuserid 奖励给谁
     * @param basemoney 奖励基数
     * @param rewordkey 奖励配置key
     * @param remark 说明
     */
    private void sendReward(PUser user,String fuserid,BigDecimal basemoney,String rewordkey,String remark,POrder order){
        BigDecimal reward = getRewardAmount(basemoney,rewordkey,user.getCoid());//计算具体奖励值
        if(reward.compareTo(BigDecimal.ZERO)>0){
            pUserMapper.addWalletByFuserid(user.getPfuserid(),reward);
            PUser pUser = pUserMapper.single(fuserid);
            BigDecimal balance = pUser.getWalletamount().subtract(pUser.getLockamount());
            addFlowWithOrderid(user,fuserid,GlobalValues.FLOW_TYPE_0.value(),reward,balance,GlobalValues.SOURCETYPE_1.value(),remark,order.getOrderid());
        }
    }

    /**
     * 转介绍购买新店体验奖励值计算
     * @param amount
     * @param rewardkey
     * @return
     */
    private BigDecimal getRewardAmount(BigDecimal amount,String rewardkey,String coid){
        String reward = ConfigCode.valueOf(rewardkey).value(coid);
        BigDecimal rewardB = new BigDecimal(reward);
        if(rewardB.compareTo(BigDecimal.ZERO)<=0){
            return BigDecimal.ZERO;
        }
        return amount.multiply(rewardB).divide(new BigDecimal("100"),2,BigDecimal.ROUND_HALF_DOWN);
    }

    /**
     * 爆品体验奖励
     */
    private void rewardBP(POrder order,PUser user){
        //上级不是合伙人则上级不享受此奖励
        if(!S.eq(user.getPlevel(),GlobalValues.PLEVEL_2.value())){
            return;
        }
        String reward = ConfigCode.valueOf("INTRODUCTION_REWARD_BP").value(user.getCoid());
        BigDecimal rewardB = new BigDecimal(reward);
        if(rewardB.compareTo(BigDecimal.ZERO)>0){
            pUserMapper.addWalletByFuserid(user.getPfuserid(),rewardB);
            PUser pUser = pUserMapper.single(user.getPfuserid());
            BigDecimal balance = pUser.getWalletamount().subtract(pUser.getLockamount());
            addFlowWithOrderid(user,user.getPfuserid(),GlobalValues.FLOW_TYPE_0.value(),rewardB,balance,GlobalValues.SOURCETYPE_4.value(),"爆品体验奖励",order.getOrderid());
        }
    }


    /**
     * 增加钱包金额流水
     * @param fuserid 得奖励的人
     * @param type 类型入0,出1
     * @param flowamount 奖励金额
     * @param balance 余额
     * @param remark 说明
     */
//    private void addFlow(PUser user,String fuserid,String type,BigDecimal flowamount,BigDecimal balance,String remark){
//        addFlow(user,fuserid,type,flowamount,balance,GlobalValues.SOURCETYPE_1.value(),remark);
//    }

    /**
     *
     * @param user
     * @param fuserid
     * @param type
     * @param flowamount
     * @param balance
     * @param sourcetype
     * @param remark
     */
    public void addFlow(PUser user,String fuserid,String type,BigDecimal flowamount,BigDecimal balance,String sourcetype,String remark){
        addFlowWithOrderid(user, fuserid, type, flowamount, balance, sourcetype, remark,null);
    }

    /**
     *
     * @param user
     * @param fuserid
     * @param type
     * @param flowamount
     * @param balance
     * @param sourcetype
     * @param remark
     */
    private void addFlowWithOrderid(PUser user,String fuserid,String type,BigDecimal flowamount,BigDecimal balance,String sourcetype,String remark,String orderid){
        PWalletFlow flow = new PWalletFlow();
        flow.setWfid(S2.UUID());
        flow.setFuserid(fuserid);//只给关系人
        flow.setCreatetime(DateUtils.getTimeNow());
        flow.setWftimestamp(new Date().getTime());
        flow.setCoid(user.getCoid());
        flow.setType(type);
        flow.setBalance(balance);
        flow.setFlowamount(flowamount);
        flow.setRemark(remark);
        flow.setSourcetype(sourcetype);//转介绍奖励
        if(S.eq(sourcetype,GlobalValues.SOURCETYPE_1.value())
                ||S.eq(sourcetype,GlobalValues.SOURCETYPE_4.value())
                ){//新店体验和爆品体验才增加
            flow.setSourcefuserid(user.getFuserid());
        }
        if(S.isNotBlank(orderid)){
            flow.setSourceorderid(orderid);
        }
        pWalletFlowMapper.insert(flow);
    }

    //endregion 现金奖励 结束


}
